package com.jiuwei.androidbasemodel.network

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import retrofit2.Response

/**
 * 网络请求示例
 * 
 * 这个类展示了如何在ViewModel中使用Retrofit进行网络请求
 * 使用了Kotlin协程和Flow来处理异步操作和数据流
 */
class NetworkRequestExample : ViewModel() {
    
    // 创建API服务实例
    private val apiService = RetrofitManager.createService(ApiService::class.java)
    
    // 用户数据状态流
    private val _userState = MutableStateFlow<UserState>(UserState.Initial)
    val userState: StateFlow<UserState> = _userState
    
    // 用户列表状态流
    private val _usersState = MutableStateFlow<UsersState>(UsersState.Initial)
    val usersState: StateFlow<UsersState> = _usersState
    
    /**
     * 获取用户信息
     * @param userId 用户ID
     */
    fun getUser(userId: String) {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading
                
                val response = apiService.getUser(userId)
                if (response.isSuccessful) {
                    response.body()?.let { user ->
                        _userState.value = UserState.Success(user)
                    } ?: run {
                        _userState.value = UserState.Error("响应体为空")
                    }
                } else {
                    _userState.value = UserState.Error("请求失败: ${response.code()}")
                }
            } catch (e: Exception) {
                _userState.value = UserState.Error(e.message ?: "未知错误")
            }
        }
    }
    
    /**
     * 获取用户列表
     * @param page 页码
     * @param pageSize 每页数量
     */
    fun getUsers(page: Int, pageSize: Int) {
        viewModelScope.launch {
            try {
                _usersState.value = UsersState.Loading
                
                val response = apiService.getUsers(page, pageSize)
                if (response.isSuccessful) {
                    response.body()?.let { users ->
                        _usersState.value = UsersState.Success(users)
                    } ?: run {
                        _usersState.value = UsersState.Error("响应体为空")
                    }
                } else {
                    _usersState.value = UsersState.Error("请求失败: ${response.code()}")
                }
            } catch (e: Exception) {
                _usersState.value = UsersState.Error(e.message ?: "未知错误")
            }
        }
    }
    
    /**
     * 创建用户
     * @param name 用户名
     * @param email 邮箱
     * @param age 年龄
     */
    fun createUser(name: String, email: String, age: Int) {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading
                
                val userRequest = UserRequest(name, email, age)
                val response = apiService.createUser(userRequest)
                
                if (response.isSuccessful) {
                    response.body()?.let { user ->
                        _userState.value = UserState.Success(user)
                    } ?: run {
                        _userState.value = UserState.Error("响应体为空")
                    }
                } else {
                    _userState.value = UserState.Error("请求失败: ${response.code()}")
                }
            } catch (e: Exception) {
                _userState.value = UserState.Error(e.message ?: "未知错误")
            }
        }
    }
    
    /**
     * 更新用户信息
     * @param userId 用户ID
     * @param name 用户名
     * @param email 邮箱
     * @param age 年龄
     */
    fun updateUser(userId: String, name: String, email: String, age: Int) {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading
                
                val userRequest = UserRequest(name, email, age)
                val response = apiService.updateUser(userId, userRequest)
                
                if (response.isSuccessful) {
                    response.body()?.let { user ->
                        _userState.value = UserState.Success(user)
                    } ?: run {
                        _userState.value = UserState.Error("响应体为空")
                    }
                } else {
                    _userState.value = UserState.Error("请求失败: ${response.code()}")
                }
            } catch (e: Exception) {
                _userState.value = UserState.Error(e.message ?: "未知错误")
            }
        }
    }
    
    /**
     * 删除用户
     * @param userId 用户ID
     */
    fun deleteUser(userId: String) {
        viewModelScope.launch {
            try {
                _userState.value = UserState.Loading
                
                val response = apiService.deleteUser(userId)
                
                if (response.isSuccessful) {
                    _userState.value = UserState.Deleted
                } else {
                    _userState.value = UserState.Error("请求失败: ${response.code()}")
                }
            } catch (e: Exception) {
                _userState.value = UserState.Error(e.message ?: "未知错误")
            }
        }
    }
}

/**
 * 用户状态密封类
 */
sealed class UserState {
    object Initial : UserState()
    object Loading : UserState()
    data class Success(val user: UserResponse) : UserState()
    object Deleted : UserState()
    data class Error(val message: String) : UserState()
}

/**
 * 用户列表状态密封类
 */
sealed class UsersState {
    object Initial : UsersState()
    object Loading : UsersState()
    data class Success(val users: List<UserResponse>) : UsersState()
    data class Error(val message: String) : UsersState()
}